<!DOCTYPE HTML>
<html>
<head>
  <script type="application/javascript" src="pc.js"></script>
</head>
<body>
<pre id="test">
<script type="application/javascript;version=1.8">
createHTML({
  bug: "1230184",
  title: "Set parameters on sender",
  visible: true
});

function parameterstest(pc) {
  ok(pc.getSenders().length > 0, "have senders");
  var sender = pc.getSenders()[0];

  var testParameters = (params, errorName, errorMsg) => {

    var validateParameters = (a, b) => {
      var validateEncoding = (a, b) => {
        is(a.rid, b.rid || "", "same rid");
        is(a.maxBitrate, b.maxBitrate, "same maxBitrate");
        is(a.scaleResolutionDownBy, b.scaleResolutionDownBy,
           "same scaleResolutionDownBy");
      };
      is(a.encodings.length, (b.encodings || []).length, "same encodings");
      a.encodings.forEach((en, i) => validateEncoding(en, b.encodings[i]));
    };

    var before = JSON.stringify(sender.getParameters());
    isnot(JSON.stringify(params), before, "starting condition");

    var p = sender.setParameters(params)
    .then(() => {
      isnot(JSON.stringify(sender.getParameters()), before, "parameters changed");
      validateParameters(sender.getParameters(), params);
      is(null, errorName || null, "is success expected");
    }, e => {
      is(e.name, errorName, "correct error name");
      is(e.message, errorMsg, "correct error message");
    });
    is(JSON.stringify(sender.getParameters()), before, "parameters not set yet");
    return p;
  };

  return [
    [{ encodings: [ { rid: "foo", maxBitrate: 40000, scaleResolutionDownBy: 2 },
                    { rid: "bar", maxBitrate: 10000, scaleResolutionDownBy: 4 }]
    }],
    [{ encodings: [{ maxBitrate: 10000, scaleResolutionDownBy: 4 }]}],
    [{ encodings: [{ maxBitrate: 40000 },
                   { rid: "bar", maxBitrate: 10000 }] }, "TypeError", "Missing rid"],
    [{ encodings: [{ rid: "foo", maxBitrate: 40000 },
                   { rid: "bar", maxBitrate: 10000 },
                   { rid: "bar", maxBitrate: 20000 }] }, "TypeError", "Duplicate rid"],
    [{}]
  ].reduce((p, args) => p.then(() => testParameters.apply(this, args)),
           Promise.resolve());
}

runNetworkTest(() => {

  test = new PeerConnectionTest();
  test.setMediaConstraints([{video: true}], [{video: true}]);
  test.chain.removeAfter("PC_REMOTE_WAIT_FOR_MEDIA_FLOW");

  // Test sender parameters.
  test.chain.append([
    function PC_LOCAL_SET_PARAMETERS(test) {
      return parameterstest(test.pcLocal._pc);
    }
  ]);

  return test.run()
    .catch(e => ok(false, "unexpected failure: " + e));
});

</script>
</pre>
</body>
</html>
